package com.ruoyi.project.wx.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.bean.EmptyUtil;
import com.ruoyi.common.utils.security.JwtTokenUtilHutool;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.erp.member.domain.ErpMember;
import com.ruoyi.project.erp.member.service.IErpMemberService;
import com.ruoyi.project.wx.miniapp.config.WxMaConfiguration;
import com.ruoyi.project.wx.miniapp.domain.MiniappDTO;
import io.swagger.annotations.*;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@Api(tags = "小程序用户相关接口")
@RequestMapping("/wx/user")
public class WxMaUserController extends BaseController {


    @Autowired
    private JwtTokenUtilHutool jwtTokenUtilHutool;

    @Autowired
    private IErpMemberService erpMemberService;


    /**
     * 13.小程序登录
     * 登陆接口
     */
    @ApiOperation(value = "用户登录")
    @ApiResponses({@ApiResponse(code = 0, message = "请求成功,返回token为其他重要接口请求的请求校验码，member为用户信息")
    })
    @PostMapping("/login")
    public AjaxResult login(MiniappDTO miniappDTO) {
        if (StringUtils.isBlank(miniappDTO.getCode())) {
            return error("empty jscode");
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(RuoYiConfig.getAppId());

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(miniappDTO.getCode());
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());

            ErpMember erpMember = new ErpMember();

            erpMember.setMemberOpenId(session.getOpenid());
            erpMember.setMemberHeadImgUrl(miniappDTO.getAvatarUrl());
            erpMember.setMemberCity(miniappDTO.getCity());
            erpMember.setMemberProvince(miniappDTO.getProvince());
            erpMember.setMemberCountry(miniappDTO.getCountry());
            erpMember.setMemberSex(miniappDTO.getGender());
            erpMember.setMemberNickname(miniappDTO.getNickName());
            erpMember.setMemberName(miniappDTO.getNickName());

            ErpMember memberInDb = erpMemberService.selectErpMemberByMemberOpenId(erpMember.getMemberOpenId());

            //根据openId查询用户
            if (EmptyUtil.isEmpty(memberInDb)) {
                //如果没查到则新增
                erpMemberService.insertErpMember(erpMember);
                memberInDb = erpMemberService.selectErpMemberByMemberOpenId(erpMember.getMemberOpenId());
                if (EmptyUtil.isEmpty(memberInDb)) {
                    return AjaxResult.error("登录失败");
                }
                memberInDb.setToken(jwtTokenUtilHutool.generateToken(memberInDb));
                return AjaxResult.success(memberInDb);
            } else {
                //如果查到了
                memberInDb.setToken(jwtTokenUtilHutool.generateToken(memberInDb));
                return AjaxResult.success(memberInDb);
            }

        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return error(e.toString());
        }
    }






    /**
     * 查询用户信息
     *
     */
    @ApiOperation(value = "查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "用户编码", required = true)
    })
    @PostMapping("/getMemberInfoById")
    public AjaxResult getMemberInfoById(Long memberId) {
        if (EmptyUtil.isEmpty(memberId)) {
            return error("用户编码为空");
        }

        ErpMember erpMember = erpMemberService.selectMemberById(memberId);
        if (EmptyUtil.isEmpty(erpMember)) {
            return error("未找到用户");
        }
        erpMember.setToken(jwtTokenUtilHutool.generateToken(erpMember));
        return AjaxResult.success(erpMember);
    }

}
